#include "crc16.h"

//-----------------------------------------------------------------------------
#define CCITT     (0x1021)

//-----------------------------------------------------------------------------
static U16 _crc(U32 n)
{
  U32 i, acc;

  for (n <<= 8, acc = 0, i = 8; i > 0; i--, n <<= 1)
  {
    acc = ((n ^ acc) & 0x8000) ? ((acc << 1) ^ CCITT) : (acc << 1);
  }

  return (U16)(acc);
}

//-----------------------------------------------------------------------------
U16 CRC16(U32 crc, U8 *buffer, U32 length)
{
  U32 i, j;

  for (i = 0; i < length; i++)
  {
    j = (crc >> 8) ^ buffer[i];
    crc = (crc << 8) ^ _crc(j);
  }

  return crc;
}
U16 MODBUS_CRC16(U8 *buffer, U16 length)
{
	U8 i;
//	U16 temp=0;
	unsigned short crc= 0xFFFF;
	U8 *target_buf;
	target_buf = buffer+2;
	if(length==0)
	{
		length=1;
	}
	while(length--)
	{
		crc^=*target_buf;
		for(i=0;i<8;i++)
		{
			if(crc&1)
			{
				crc>>=1;
				crc^=0xA001;
			}
			else
			{
				crc>>=1;
			}
		}
		target_buf++;	
	}
//	temp = crc << 8;
//	crc = temp + (crc >>8);
	
	return(crc);
}


